package com.palm.hubo2o.util;

import android.os.CountDownTimer;

import com.palm.hubo2o.event.IssueCountEvent;
import com.palm.hubo2o.event.IssueEvent;
import com.palm.hubo2o.event.IssueHistoryEvent;
import com.palm.hubo2o.model.Issue;
import com.palm.hubo2o.model.LazyResBody;
import com.palm.hubo2o.model.PastIssueParams;
import com.palm.hubo2o.network.ApiService;
import com.palm.hubo2o.network.PalmRetrofit;
import com.palm.hubo2o.network.Request;
import com.palm.hubo2o.network.Result;
import com.palm.palmutils.MainHandler;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import de.greenrobot.event.EventBus;
import retrofit2.Response;

/**
 * Created by dest1 on 2015/11/6.
 */
public class IssueCenter {
    private final static String TAG = "IssueCenter";
    private static final long ISSUE_TASK_PERIOD = 10 * 1000;
    private static final int ISSUE_HISTORY_SIZE = 10;
    //期次列表100期
    private final List<Issue> ssqList = new ArrayList<>();//
    private final List<Issue> k3List = new ArrayList<>();
    private final List<Issue> d3List = new ArrayList<>();
    private final List<Issue> qlcList = new ArrayList<>();
    //当前期次
    private Issue ssq;
    private Issue k3;
    private Issue d3;
    private Issue qlc;

    private Timer issueTimer;

    private static IssueCenter instance;
    private final ApiService mApiService;

    private IssueCenter() {
        super();
        issueTimer = new Timer(TAG);
        mApiService = PalmRetrofit.getInstance().getApi();
    }

    public static IssueCenter open() {
        if (instance == null) {
            instance = new IssueCenter();
        }
        return instance;
    }

    /**
     * 外部调用加载历史期次
     */
    public void startLoadHistory(EnumCode.gameId gameId) {
        issueTimer.schedule(new IssueTask(gameId, true), 0);
    }

    public void startLoadHistory(EnumCode.gameId gameId, boolean first) {
        IssueTask it = new IssueTask(gameId, true);
        it.setFirst(true);
        issueTimer.schedule(it, 0);
    }

    public void startLoadCurrent(EnumCode.gameId gameId) {
        issueTimer.schedule(new IssueTask(gameId), 0, ISSUE_TASK_PERIOD);
    }

    public List<Issue> switchIssueList(EnumCode.gameId lotteryId) {
        List<Issue> tempList;
        switch (lotteryId) {
            case D3:
                tempList = d3List;
                break;
            case HBP3:
                tempList = k3List;
                break;
            case QLC:
                tempList = qlcList;
                break;
            case SSQ:
                tempList = ssqList;
                break;
//            case C522:
//                tempList = c225List;
//                break;
            default:
                tempList = new ArrayList<>();
                break;
//                throw new IllegalArgumentException("wtf lottery?");
        }
        return tempList;
    }

    public Issue switchIssue(EnumCode.gameId lotteryId) {
        Issue issue = null;
        switch (lotteryId) {
            case D3:
                issue = d3;
                break;
            case HBP3:
                issue = k3;
                break;
            case QLC:
                issue = qlc;
                break;
            case SSQ:
                issue = ssq;
                break;
//            case C522:
//                issue = c225;
//                break;
            default:
//                throw new IllegalArgumentException("wtf lottery?");
        }
        return issue;
    }

    private void setCurrentIssue(Issue i) {
        switch (i.gameId) {
            case SSQ:
                ssq = i;
                break;
            case HBP3:
                k3 = i;
                break;
            case D3:
                d3 = i;
                break;
            case QLC:
                qlc = i;
                break;
//            case C522:
//                c225 = i;
//                break;
            default:
                throw new IllegalArgumentException("no lottery " + i.gameId);
        }
    }

    private void clearIssue(EnumCode.gameId lotteryId) {

        switch (lotteryId) {
            case D3:
                d3.issueNo = -1;
                break;
            case HBP3:
                k3.issueNo = -1;
                break;
            case QLC:
                qlc.issueNo = -1;
                break;
            case SSQ:
                ssq.issueNo = -1;
                break;
//            case C522:
//                c225.issueNo = -1;
//                break;
            default:
                throw new IllegalArgumentException("wtf lottery?");
        }


    }

    private boolean loadCurrentIssue(EnumCode.gameId lotteryId) {
        Request<Issue> request = new Request<>();
        Issue temp = new Issue();
        temp.gameId = lotteryId;
        request.setBody(temp);
        try {
            Response<Result<Issue>> response = mApiService.queryCurrentIssue(request).execute();
            if (response.isSuccessful() && response.body().isSuccessful()) {
                final Result<Issue> r = response.body();
//                if (!"1".equa
                setCurrentIssue(r.getBody());
                EventBus.getDefault().post(new IssueEvent(lotteryId));
                MainHandler.getInstance().post(new Runnable() {
                    @Override
                    public void run() {
                        new IssueCount(r.getBody().endTime.getTime(), r.getServerTime().getTime(), r.getBody().gameId).start();//开启期次倒计时
                    }
                });
//                issueTimer.schedule(new IssueTask(r.getBody().gameId),//倒计时开奖时间，开出以后轮询获取下一期
//                        r.getBody().prizeTime.getTime() - response.body().getServerTime().getTime(), ISSUE_TASK_PERIOD);
//            issueTimer.schedule(new IssueTask(lotteryId, true), 0);
                startLoadHistory(lotteryId);//获取上一期
                return true;
            } else {
                return false;
            }
        } catch (IOException | NullPointerException e) {
            e.printStackTrace();
            return false;
        }

    }

    private boolean loadLastIssue(EnumCode.gameId gameId, boolean first) {


        List<Issue> issueList = switchIssueList(gameId);
        if (issueList.size() < ISSUE_HISTORY_SIZE) {
            issueList.clear();
        }
        PastIssueParams p = new PastIssueParams(gameId.name());
        p.setGameId(gameId.name());
        p.setPage(1);
        p.setSize(first ? 1 : ISSUE_HISTORY_SIZE);
        Request<PastIssueParams> request = new Request<>();
        request.setBody(p);
        try {
            Response<Result<LazyResBody<Issue>>> response = mApiService.queryPastIssue(request).execute();
            if (response.isSuccessful() && response.body().isSuccessful()) {
                final List<Issue> tempList = response.body().getBody().getList();
                if (issueList.size() == 0) {
                    issueList.addAll(tempList);
                } else {
                    issueList.remove(0);
                    issueList.add(0, tempList.get(0));
                }
                EventBus.getDefault().post(new IssueHistoryEvent(gameId));
                return true;
            } else {
                return false;
            }
        } catch (IOException | NullPointerException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 期次倒计时
     */
    private class IssueCount extends CountDownTimer {

        private final EnumCode.gameId gameId;//倒计时期次,单位秒
        private IssueCountEvent event;

        public IssueCount(long endTime, long serverTime, EnumCode.gameId gameId) {
            super(endTime - serverTime, gameId == EnumCode.gameId.HBP3 ? 1000 : 1000 * 60 * 10);
            this.gameId = gameId;
            event = new IssueCountEvent(gameId, -1);
        }


        @Override
        public void onTick(long millisUntilFinished) {
            event.timeLeft = millisUntilFinished;
            EventBus.getDefault().post(event);
        }

        @Override
        public void onFinish() {
            event.timeLeft = 0;
            EventBus.getDefault().post(event);
            clearIssue(gameId);
//            issueTimer.schedule(new IssueTask(mIssue.gameId),//倒计时开奖时间，开出以后轮询获取下一期
//                    mIssue.prizeTime.getTime() - mIssue.sallEndTime.getTime(), ISSUE_TASK_PERIOD);
        }
    }

    /**
     * 期次获取线程
     */
    private class IssueTask extends TimerTask {
        EnumCode.gameId gameId;
        boolean history;
        boolean first;

        public IssueTask(EnumCode.gameId gameId) {
            this(gameId, false);
        }


        public IssueTask(EnumCode.gameId gameId, boolean history) {
            this.gameId = gameId;
            this.history = history;
        }

        public void setFirst(boolean first) {
            this.first = first;
        }

        @Override
        public void run() {
            if (!history) {
                if (loadCurrentIssue(gameId))
                    cancel();
            } else {
                if (loadLastIssue(gameId, first))
                    cancel();
            }
        }
    }
}
